import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/bloc/auth_cubit.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/entity/user.dart';
import 'package:grint/utils/whisper.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/edit_profile_dialog.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/widget/pop_tool.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class SettingsPage extends StatefulWidget {
  const SettingsPage({super.key});

  @override
  State<SettingsPage> createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  late TextEditingController _descriptionController;
  Timer? _debounceTimer;

  @override
  void initState() {
    super.initState();
    _descriptionController = TextEditingController();
  }

  @override
  void dispose() {
    _descriptionController.dispose();
    _debounceTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 背景图
          Positioned.fill(
            child: Image.asset('assets/images/commonBg.png', fit: BoxFit.cover),
          ),

          // 返回按钮和标题
          Positioned(
            top: 44.h,
            left: 16.w,
            right: 16.w,
            child: Row(
              children: [
                BlackButton(
                  icon: IconFontIcons.iconArrowLeft,
                  onTap: () => context.pop(),
                ),
                Expanded(
                  child: Center(
                    child: MyText(
                      text: 'Settings',
                      type: TextType.rubik,
                      fontSize: 26.sp,
                      color: AppColors.black,
                    ),
                  ),
                ),
                SizedBox(width: 36.w),
              ],
            ),
          ),

          SafeArea(
            child: Padding(
              padding: EdgeInsets.only(top: 44.h),
              child: BlocBuilder<AuthCubit, AuthState>(
                builder: (context, authState) {
                  final currentUser = authState.currentUser;

                  // 更新描述控制器的文本（只在用户改变时更新）
                  WidgetsBinding.instance.addPostFrameCallback((_) {
                    if (currentUser != null &&
                        _descriptionController.text !=
                            currentUser.description) {
                      _descriptionController.text = currentUser.description;
                    }
                  });

                  return Column(
                    children: [
                      Expanded(
                        child: SingleChildScrollView(
                          padding: EdgeInsets.all(16.w),
                          child: Column(
                            children: [
                              SizedBox(height: 14.h),
                              Center(
                                child: Column(
                                  children: [
                                    Stack(
                                      children: [
                                        Container(
                                          width: 124.w,
                                          height: 124.w,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(
                                              20.r,
                                            ),
                                            color: AppColors.tabBlue,
                                          ),
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.circular(
                                              20.r,
                                            ),
                                            child: _buildUserAvatar(
                                              currentUser?.avatar ??
                                                  'assets/images/avatar-one.png',
                                            ),
                                          ),
                                        ),

                                        // 编辑按钮
                                        Positioned.fill(
                                          child: GestureDetector(
                                            onTap:
                                                () =>
                                                    _handleAvatarEdit(context),
                                            child: Center(
                                              child: Icon(
                                                IconFontIcons.iconXiangji,
                                                size: 32.w,
                                                color: Colors.white,
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),

                                    SizedBox(height: 12.h),

                                    // 用户名和编辑按钮
                                    GestureDetector(
                                      onTap:
                                          () => _handleNameEdit(
                                            context,
                                            currentUser,
                                          ),
                                      child: Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          Icon(
                                            IconFontIcons.iconEdit2,
                                            size: 18.w,
                                            color: AppColors.black,
                                          ),
                                          SizedBox(width: 8.w),
                                          MyText(
                                            text:
                                                currentUser?.name ?? 'Visitor',
                                            type: TextType.rubik,
                                            fontSize: 18.sp,
                                            fontWeight: FontWeight.bold,
                                            color: Colors.black,
                                            decoration:
                                                TextDecoration.underline,
                                          ),
                                        ],
                                      ),
                                    ),

                                    SizedBox(height: 16.h),

                                    // 用户描述输入框
                                    Container(
                                      width: double.infinity,
                                      height: 90.h,
                                      padding: EdgeInsets.all(16.w),
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(
                                          16.r,
                                        ),
                                        border: Border.all(
                                          color: const Color(0xFFE9ECEF),
                                          width: 1,
                                        ),
                                      ),
                                      child: TextField(
                                        controller: _descriptionController,
                                        maxLines: 3,
                                        style: TextStyle(
                                          fontSize: 14.sp,
                                          color: AppColors.black,
                                        ),
                                        decoration: InputDecoration(
                                          hintText: 'Tell us about yourself...',
                                          hintStyle: TextStyle(
                                            fontSize: 14.sp,
                                            color: AppColors.textGrey,
                                          ),
                                          border: InputBorder.none,
                                        ),
                                        onChanged: _handleDescriptionChange,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(height: 24.h),

                              Container(
                                padding: EdgeInsets.all(16.w),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(20.r),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    MyText(
                                      text: 'System Settings',
                                      type: TextType.rubik,
                                      fontSize: 20.sp,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black,
                                    ),

                                    InkWell(
                                      onTap: () async {
                                        await launchUrl(
                                          Uri.parse(
                                            'https://www.freeprivacypolicy.com/live/59097e95-a3c0-4157-9233-a2c444911c33',
                                          ),
                                          mode: LaunchMode.inAppBrowserView,
                                        );
                                      },
                                      child: Padding(
                                        padding: EdgeInsets.symmetric(
                                          vertical: 16.h,
                                        ),
                                        child: Row(
                                          children: [
                                            Expanded(
                                              child: MyText(
                                                text: 'Privacy Policy',
                                                type: TextType.miSans,
                                                fontSize: 14.sp,
                                                color: Colors.black,
                                              ),
                                            ),
                                            Icon(
                                              IconFontIcons.iconArrowRight,
                                              color: Colors.grey,
                                              size: 18.w,
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),

                                    Divider(
                                      height: 1,
                                      color: Colors.grey.withAlpha(50),
                                    ),

                                    InkWell(
                                      onTap: () async {
                                        await launchUrl(
                                          Uri.parse(
                                            'https://www.freeprivacypolicy.com/live/318cba43-6245-4df5-b64d-c9b31c4ac205',
                                          ),
                                          mode: LaunchMode.inAppBrowserView,
                                        );
                                      },
                                      child: Padding(
                                        padding: EdgeInsets.symmetric(
                                          vertical: 16.h,
                                        ),
                                        child: Row(
                                          children: [
                                            Expanded(
                                              child: MyText(
                                                text: 'Terms Of service',
                                                type: TextType.miSans,
                                                fontSize: 14.sp,
                                                color: Colors.black,
                                              ),
                                            ),
                                            Icon(
                                              IconFontIcons.iconArrowRight,
                                              color: Colors.grey,
                                              size: 18.w,
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),

                                    Divider(
                                      height: 1,
                                      color: Colors.grey.withAlpha(50),
                                    ),

                                    // 删除账号
                                    InkWell(
                                      onTap: () {
                                        PopTool.tanChuTongYongKuang(
                                          'Delete Account',
                                          'Are you sure you want to delete your account? This action cannot be undone.',
                                          fouDingCi: 'Cancel',
                                          kenDingCi: 'Delete',
                                          guanBiHuiDiao: () {},
                                          queRenHuiDiao: () {
                                            _handleDeleteAccount();
                                          },
                                        );
                                      },
                                      child: Padding(
                                        padding: EdgeInsets.symmetric(
                                          vertical: 16.h,
                                        ),
                                        child: Row(
                                          children: [
                                            Expanded(
                                              child: MyText(
                                                text: 'Delete Account',
                                                type: TextType.miSans,
                                                fontSize: 14.sp,
                                                color: Colors.black,
                                              ),
                                            ),
                                            Icon(
                                              IconFontIcons.iconArrowRight,
                                              color: Colors.grey,
                                              size: 18.w,
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                    Divider(
                                      height: 1,
                                      color: Colors.grey.withAlpha(50),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),

                      // 登出按钮
                      Padding(
                        padding: EdgeInsets.all(16.w),
                        child: Container(
                          width: double.infinity,
                          height: 54.h,
                          decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(14.r),
                          ),
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.black,
                              foregroundColor: Colors.white,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(14.r),
                              ),
                              elevation: 0,
                            ),
                            onPressed: () {
                              PopTool.tanChuTongYongKuang(
                                'Confirm Logout',
                                'Are you sure you want to log out?',
                                fouDingCi: 'Cancel',
                                kenDingCi: 'Log Out',
                                guanBiHuiDiao: () {},
                                queRenHuiDiao: () {
                                  // 执行登出逻辑
                                  context.read<AuthCubit>().logout().then((_) {
                                    context.go('/home');
                                  });
                                },
                              );
                            },
                            child: MyText(
                              text: 'Log Out',
                              type: TextType.rubik,
                              fontSize: 18.sp,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserAvatar(String avatarPath) {
    if (avatarPath.startsWith('/') || avatarPath.contains('Documents')) {
      return Image.file(
        File(avatarPath),
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Image.asset('assets/images/avatar-one.png', fit: BoxFit.cover);
        },
      );
    } else {
      return Image.asset(avatarPath, fit: BoxFit.cover);
    }
  }

  void _handleAvatarEdit(BuildContext context) async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: const AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
      ),
    );

    if (result != null && result.isNotEmpty && mounted) {
      try {
        final AssetEntity asset = result.first;
        final File? imageFile = await asset.file;

        if (imageFile != null && mounted) {
          final String avatarPath = imageFile.path;

          final authCubit = context.read<AuthCubit>();

          final success = await authCubit.updateUserProfile(avatar: avatarPath);

          if (mounted) {
            if (success) {
              Whisper.murmur('Avatar updated successfully');
            } else {
              Whisper.hiss('Failed to update avatar');
            }
          }
        }
      } catch (e) {
        if (mounted) {
          Whisper.hiss('Error updating avatar: $e');
        }
      }
    }
  }

  void _handleNameEdit(BuildContext context, User? currentUser) {
    if (currentUser == null) return;

    EditProfileHelper.showEditProfileDialog(
      context: context,
      user: currentUser,
      onConfirm: (name, description) async {
        final success = await context.read<AuthCubit>().updateUserProfile(
          name: name,
          description: description,
        );

        if (success && mounted) {
          Whisper.murmur('Profile updated successfully');
        }
      },
    );
  }

  void _handleDescriptionChange(String description) {
    _debounceTimer?.cancel();

    _debounceTimer = Timer(const Duration(seconds: 2), () {
      _updateUserDescription(description);
    });
  }

  void _updateUserDescription(String description) async {
    if (!mounted) return;

    try {
      final authCubit = context.read<AuthCubit>();
      final success = await authCubit.updateUserProfile(
        description: description,
      );

      if (mounted && success) {
        Whisper.murmur('Description updated');
      }
    } catch (e) {
      if (mounted) {
        Whisper.hiss('Failed to update description: $e');
      }
    }
  }

  void _handleDeleteAccount() async {
    if (!mounted) return;

    try {
      Whisper.chant(message: 'Deleting account...');

      await Future.delayed(const Duration(seconds: 2));

      if (!mounted) return;

      Whisper.silence();

      Whisper.murmur('Account deleted successfully');

      await Future.delayed(const Duration(milliseconds: 800));

      if (!mounted) return;

      await context.read<AuthCubit>().logout();

      if (mounted) {
        context.go('/home');
      }
    } catch (e) {
      Whisper.silence();

      if (mounted) {
        Whisper.hiss('Failed to delete account: $e');
      }
    }
  }
}
